<template>
  <div class="">
    <el-button type="primary" style="margin-left: 12px;" size="mini" @click="handleClick">导入JSON</el-button>
    <input type="file" class="importInput" accept=".json" id="import" ref="import" @change="handleImport" />
  </div>
</template>

<script>
  import InDB from "../utils/initDB.js"
  export default {
    props: {
      store: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        storeList: [
          'enSTrackState',
          'STrackStages',
          'actionsPool',
          'CfgSTrackControl',
          'controllerTools',
          'CfgSTrackRunner',
          'CfgCombineControlDefine',
          'CfgSTrackRunner',
          'CfgActionElment',
          'AutoActCode',
          'defineTools',
        ]
      }
    },
    methods: {
      handleClick() {
        this.$refs.import.click()
      },
      handleImport() {
        let store = this.storeList[this.store]
        let file = this.$refs.import.files[0]
        let reader = new FileReader()
        reader.readAsText(file)
        reader.onload = (res) => {
          let result = JSON.parse(res.currentTarget.result)
          this.$confirm('是否确认导入覆盖当前内容?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            let promiseList = []
            for (let i = 0; i < result.length; i++) {
              promiseList.push(InDB[store].put({
                ...result[i]
              }))

            }
            Promise.all(promiseList).then((res) => {
              InDB[store].all().then(res => {
                loading.close()
                this.$message({
                  type: 'info',
                  message: '导入成功'
                });
                this.$emit('handleImport', res)
              })
            }).catch(err => {
              this.$message({
                type: 'info',
                message: '导入失败'
              });
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
      },
    }
  }
</script>

<style scoped="">
  .importInput {
    margin-left: 20px;
    display: none;
  }
</style>
